<script setup>
import { ref, watch } from 'vue'
import BaseInput from '../base/BaseInput.vue'
import { sendCode } from '@/api/login'
import useLocale from '@/composables/useLocale'

const props = defineProps({
    phone: {
        type: String,
        default: '',
    },
    modelValue: {
        type: String,
        default: '',
    },
    sendType: {
        type: String,
        default: 'login',
    },
})

const emit = defineEmits(['update:modelValue'])

const { t } = useLocale()

const countdown = ref(0)

function startCountdown() {
    countdown.value = 60
    const timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--
        } else {
            clearInterval(timer)
        }
    }, 1000)
}

async function handleSendCode() {
    if (countdown.value > 0) {
        return
    }
    if (!props.phone) {
        uni.showToast({
            title: t('pleaseEnterPhoneNumber'),
            icon: 'none',
        })
        return
    }
    startCountdown()
    const resp = await sendCode({
        phoneOrEmail: props.phone,
        sendType: 0,
        type: props.sendType,
    })
    if (resp.status === 200) {
        uni.showToast({
            title: t('verificationCodeSent'),
            icon: 'none',
        })
    }
}

const val = ref(props.modelValue)
watch(
    () => props.modelValue,
    (newVal) => {
        val.value = newVal
    },
)

watch(
    () => val.value,
    (newVal) => {
        emit('update:modelValue', newVal)
    },
)
</script>

<template>
    <BaseInput v-bind="$attrs" v-model="val" type="number">
        <template #suffix>
            <view
                class="ml-3 whitespace-nowrap text-xs text-zinc-950"
                @click="handleSendCode"
            >
                <template v-if="countdown > 0">
                    {{ t('resendAfterSeconds', [countdown]) }}
                </template>
                <template v-else>{{ t('getVerificationCode') }}</template>
            </view>
        </template>
    </BaseInput>
</template>
